package com.sunday.aomicaichang.ui.coupon;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sunday.common.base.BaseFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.adpter.CouponAdapter;
import com.sunday.aomicaichang.base.BaseApp;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.model.Coupon;
import com.sunday.member.utils.SignUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class CouponFragment extends BaseFragment {


    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private int type;
    private String statuses;
    private String amount;
    private CouponAdapter adapter;
    private List<Coupon> dataSet=new ArrayList<>();
    private long memberId;
    public static CouponFragment newInstance(String statuses,String amount) {
        CouponFragment fragment = new CouponFragment();
        Bundle bundle = new Bundle();
        bundle.putString("statuses", statuses);
        bundle.putString("amount", amount);
        fragment.setArguments(bundle);

        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_order_list, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getArguments() != null) {
            statuses=getArguments().getString("statuses");
            amount=getArguments().getString("amount");
        }
        initRecyclerView();
        getData();
    }

    private int lastVisibleItem=1;
    private boolean isCanloadMore;
    private LinearLayoutManager layoutManager;
    private void initRecyclerView(){
        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        layoutManager=new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).drawable(R.drawable.horizontal_space_divider).build());
        adapter=new CouponAdapter(mContext,getActivity(),amount);
        adapter.setmData(dataSet);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo=1;
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo=1;
                getData();
            }
        });
    }


    private int pageNo=1;
    private int pageSize=10;
    private void getData() {

        String nonce= MD5Utils.random();
        String[] str1=new String[]{"amount","memberId","status","pageSize","pageNumber","nonce"};
        String[] str2=new String[]{amount,String.valueOf(memberId),statuses,String.valueOf(pageSize),String.valueOf(pageNo),nonce};
        showLoadingDialog(0);
        memberId = BaseApp.getInstance().getMember().getId();
        Call<ResultDO<List<Coupon>>> call= ApiClient.getApiAdapter().getMemberCoupon(amount,memberId,statuses,pageSize,pageNo,nonce,
                SignUtil.getSign(str1,str2));
        call.enqueue(new Callback<ResultDO<List<Coupon>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Coupon>>> call, Response<ResultDO<List<Coupon>>> response) {
                ptrFrame.refreshComplete();
                dissMissDialog();
                if (isFinish||response.body()==null){return;}
                if (response.body().getCode()==0){
                    if (response.body().getResult()==null){return;}
                    if (pageNo==1){
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult());
                    if (response.body().getResult().size()==10){
                        isCanloadMore=true;
                        pageNo++;
                    }else {
                        isCanloadMore=false;
                    }
                    if (dataSet.size()>0){
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    }else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.setmData(dataSet);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Coupon>>> call, Throwable t) {
                ptrFrame.refreshComplete();
            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
